package com.zys.hotel_management.interceptor;

/**
 * @Author:Soyo
 * @Description:
 * @Create: 2025/5/23
 */

import com.zys.hotel_management.common.Response;
import com.zys.hotel_management.entity.Customer;
import com.zys.hotel_management.service.AdminService;
import com.zys.hotel_management.service.CustomerService;
import com.zys.hotel_management.utils.JwtUtils;
import com.zys.hotel_management.utils.UserContext;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

public class JwtInterceptor implements HandlerInterceptor {


    // 添加@Resource
    @Resource
    private CustomerService customerService;
    @Resource
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getRequestURI().contains("/login")) {
            return true;
        }
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            sendErrorResponse(response, 401, "未提供有效的 JWT 令牌");
            return false;
        }
        token = token.substring(7);
        try {
            String username = JwtUtils.validateToken(token); // 假设返回username
            Customer customer = customerService.getByUsername(username);
            if (customer != null) {
                UserContext.setUser(customer);
                return true;
            }
            if (!Objects.isNull(adminService.getByUsername(username))){
                return true;
            }
            sendErrorResponse(response, 401, "用户不存在");
            return false;
        } catch (Exception e) {
            sendErrorResponse(response, 401, "无效的 JWT 令牌: " + e.getMessage());
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.clear();
    }

    private void sendErrorResponse(HttpServletResponse response, int code, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(code);
        PrintWriter out = response.getWriter();
        out.println(Response.fail(code, message).toString());
        out.flush();
        out.close();
    }
}